<!--
 * @Author: lxw
 * @Date: 2021-02-22 09:42:41
 * @Description: 回到顶部组件
 -->
<template>
  <div v-show="isShow" class="back-top" @click="backTop">
    <v-icon :class="iconClass">mdi-rocket</v-icon>
  </div>
</template>

<script>
export default {
  name: 'BackTop',
  data () {
    return {
      iconClass: '',
      isShow: false
    }
  },
  mounted () {
    this.wrapEl = document.querySelector('.app-main')

    this.wrapEl.addEventListener('scroll', this.showBackTop)
  },

  beforeDestroy () {
    this.wrapEl.removeEventListener('scroll', this.showBackTop)
  },

  methods: {
    backTop () {
      this.iconClass = 'fly'

      this.backTopTimer = setInterval(() => {
        if (this.wrapEl.scrollTop <= 0) {
          clearInterval(this.backTopTimer)
        }
        this.wrapEl.scrollTop = this.wrapEl.scrollTop - (this.wrapEl.scrollTop / 10)
      }, 1)

      setTimeout(() => {
        this.iconClass = ''
      }, 1000)
    },
    showBackTop () {
      this.isShow = this.wrapEl.scrollTop > 100
    }
  }
}
</script>

<style scoped lang="scss">
.back-top {
  position: fixed;
  right: 50px;
  bottom: 50px;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  background: $color-primary;
  cursor: pointer;

  &:hover {
    .v-icon {
      animation: ready 1s linear;
    }
  }

  .v-icon.fly {
    animation: fly .5s;
  }
}

@keyframes ready {
  0% {
    transform: translateY(10px);
  }
  20% {
    transform: translateY(-10px);
  }
  40% {
    transform: translateY(6px);
  }
  80% {
    transform: translateY(-6px);
  }
  100% {
    transform: translateY(0);
  }
}

@keyframes fly {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(-500px);
  }
}
</style>
